<template>
  <div>
    <el-card class="box-card">
      <el-row :gutter="20" class="my-3">
        <el-col :span="4">
          <button
            @click="delAllSelection"
            type="button"
            class="el-button handle-del el-button--primary"
          >
            <i class="el-icon-delete"></i>
            <span>批量删除</span>
          </button>
        </el-col>

        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="centerDialogVisible = true">
              <i class="el-icon-plus"></i>
              <span>添加用户</span>
            </el-button>
          </div>
        </el-col>

        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" v-model="searchContent" clearable>
              <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
            </el-input>
          </div>
        </el-col>
      </el-row>

      <!-- 用户列表区 -->
      <el-table
        border
        stripe
        :data="userList"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
      >
        <el-table-column type="selection" show-overflow-tooltip></el-table-column>

        <el-table-column
          type="index"
          :index="indexSort"
          sortable
          align="center"
          label="#"
          width="50"
        ></el-table-column>
        <el-table-column align="center" prop="name" label="保姆姓名"></el-table-column>
        <el-table-column align="center" label="头像(查看大图)">
          <template #default="scope">
            <el-image
              class="table-td-headPortrait"
              :src="scope.row.img"
              :preview-src-list="[scope.row.img]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="type" show-overflow-tooltip label="服务类型"></el-table-column>
        <!-- <el-table-column align="center" prop="user.phone" label="电话"></el-table-column> -->
        <el-table-column align="center" prop="education" label="学历"></el-table-column>
        <el-table-column align="center" prop="sex" label="性别"></el-table-column>
        <el-table-column align="center" prop="birthday" label="出生日期年龄"></el-table-column>
        <el-table-column align="center" width="180px" label="操作">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="修改当前用户信息"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showMessage(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除当前用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteid(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加用户 -->

      <el-dialog
        title="添加保姆信息"
        :visible.sync="centerDialogVisible"
        width="50%"
        center
        @close="addDialogClose"
      >
        <!-- 添加表单内容区域 -->
        <el-form
          :model="addForm"
          status-icon
          :rules="addFromRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item label="保姆姓名" prop="username">
            <el-input type="text" clearable v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="服务类型" prop="password">
            <el-input type="password" clearable show-password v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="学历" prop="phone">
            <el-input type="text" clearable v-model="addForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="出生年龄" prop="email">
            <el-input type="text" clearable v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item class="d-flex">
            <el-radio v-model="addForm.gender" label="男">男</el-radio>
            <el-radio v-model="addForm.gender" label="女">女</el-radio>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="add">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页 -->

      <div class="row">
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            background
            :page-sizes="[4, 6, 8]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 修改用户信息 -->
    <el-dialog title="修改用户信息" :visible.sync="centerDialogVisible2" width="50%" center>
      <!-- 表单内容区域 -->
      <el-form
        :model="editForm"
        status-icon
        :rules="addFromRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item hidden label="id" prop="id">
          <el-input type="hidden" v-model="editForm.id"></el-input>
        </el-form-item>
        <el-form-item label="保姆名" prop="username">
          <el-input type="text" clearable v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出生日期" prop="phone">
          <el-input type="text" clearable v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学历" prop="address">
          <el-input type="text" clearable v-model="editForm.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item class="d-flex">
          <el-radio
            v-model="editForm.roles"
            v-for="(item,index) in roles"
            :label="index+1"
            :key="index"
          >{{item}}</el-radio>
        </el-form-item>

        <el-form-item class="d-flex">
          <el-radio v-model="editForm.sex" label="男">男</el-radio>
          <el-radio v-model="editForm.sex" label="女">女</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import qs from 'qs'
import axios from 'axios'
export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value !== this.editFormPassword.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 分页
      total: 0,
      pageSize: 6,
      currentPage: 1,
      searchContent: '', // 搜索内容
      userList: [],
      // 弹出框
      centerDialogVisible: false,
      centerDialogVisible2: false,
      dialogVisible: false,
      addForm: {},
      roles: [], // 角色选择
      //添加
      addForm: {
        username: '',
        password: '',
        phone: '',
        email: '',
        gender: '男',
      },
      editForm: {
        id: 21,
        username: '',
        phone: '',
        address: '',
        roles: '',
        sex: '',
        type: '',
      },

      //验证规则
      addFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        checkPass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' },
        ],
        phone: [{ message: '请输出生日期', trigger: 'blur' }],
        address: [
          { message: '请输入学历', trigger: 'blur' },
          {
            message: '请输入正确的学历',
            trigger: 'blur',
          },
        ],
        role: [
          {
            required: true,
            message: '请输入从角色名称',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      //删除列表

      multipleSelection: [], //批量删除列表
    }
  },
  created() {
    this.getUserList()
    this.getRoles()
  },
  methods: {
    // 获取所有用户
    async getUserList() {
      const { data } = await this.$http.get(
        '/nanny/list?' +
          qs.stringify({
            userId: this.$store.getters.getUserInfo.id,
            current: this.currentPage,
            size: this.pageSize,
          })
      )

      if (data.code == 200) {
        this.userList = data.data.records
        this.total = data.data.total
      }
    },

    // 添加用户信息
    async add() {
      this.$refs.addFormRef.validate(async (valid, obj) => {
        if (valid) {
          let formdata = new FormData()
          const { data } = await this.$http.post('/nanny/save', {
            // username: this.addForm.username,
            // password: this.addForm.password,
            // phone: this.addForm.phone,
            // email: this.addForm.email,
            // gender: this.addForm.gender,
          })
          if (data.code == 200) {
            this.addresetForm()
            this.$message.success('添加成功！')
            this.getUserList()
          } else {
            this.$message.error('添加失败!')
          }
        } else {
          this.$message.error('表单填写有误，请检查后提交！')
        }
        this.centerDialogVisible = false
      })
    },
    // 分页
    handleSizeChange(pageSize) {
      this.currentPage = 1
      this.pageSize = pageSize
      this.getUserList()
    },
    // 跳转页数
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getUserList()
    },
    // 查询用户信息
    async search() {
      const { data } = await this.$http.get(
        '/nanny/list?' +
          qs.stringify({
            userId: this.$store.getters.getUserInfo.id,
            name: this.searchContent,
            current: this.currentPage,
            size: this.pageSize,
          })
      )

      if (data.code == 200) {
        this.userList = data.data.records
        this.total = data.data.total
        this.searchContent = ''
      } else {
        this.$message.error('查询用户不存在')
      }
    },
    // 获取角色列表
    async getRoles() {
      const { data } = await this.$http.get('/nanny/type/list')

      if (data.code == 200) {
        for (const key in data.data.records) {
          const element = data.data.records[key].name
          this.roles.push(element)
        }
      }
    },
    // 修改用户信息前获取点击用户的信息
    showMessage(row) {
      this.editForm.id = row.id

      this.editForm.username = row.name
      this.editForm.address = row.education
      this.editForm.phone = row.birthday
      this.editForm.sex = row.sex
      this.editForm.type = row.type

      for (let index = 0; index < this.roles.length; index++) {
        let num = index
        if (row.type == this.roles[index]) {
          this.editForm.roles = num + 1
        }
      }

      this.centerDialogVisible2 = true
    },

    // 修改用户信息
    edit() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          let formData = new FormData()

          for (let index = 0; index <= this.roles.length; index++) {
            let num = index
            if (this.editForm.roles == index) {
              this.editForm.type = this.roles[num - 1]
            }
          }

          console.log(this.editForm.roles)

          let nanny = {
            id: this.editForm.id,
            name: this.editForm.username,
            sex: this.editForm.sex,
            type: this.editForm.type,
          }
          formData.append(
            'nanny',
            new Blob([JSON.stringify(nanny)], {
              type: 'application/json',
            })
          )

          axios
            .post(
              '/nanny/update', //序列化对象数组
              formData,
              { headers: { 'Content-Type': 'multipart/form-data' } }
            )
            .then((response) => {
              if (response.data.code == 200) {
                this.$message.success('修改成功！')
                this.getUserList()
              } else {
                this.$message.error('修改失败！')
              }
            })
        } else {
          this.$message.error('表单填写有误，请检查后提交！')
        }
        this.centerDialogVisible2 = false
      })
    },

    // 删出用户信息
    async deleteid(row) {
      const confirmresult = await this.$confirm(
        '此操作将永久删除该该用户,不可恢复， 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmresult != 'confirm') {
        return this.$message.info('已取消删除！！')
      } else {
        let did = []
        did.push(row.id)
        const { data } = await this.$http.post('/nanny/delete', did)
        if (data.code == 200) {
          this.$message.success('成功删除了 ' + row.username + '用户')
          this.getUserList()
        } else if (data.code == 400) {
          this.$message.error(data.message)
        } else {
          this.$message.error('删除失败')
        }
        this.centerDialogVisible2 = false
      }
    },
    // 监听哪些行数改变
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量删除按钮
    async delAllSelection() {
      const length = this.multipleSelection.length
      let delList = []
      for (let i = 0; i < length; i++) {
        delList.push(this.multipleSelection[i].id)
      }
      const { data } = await this.$http.post('/nanny/delete', delList)
      if (data.code == 200) {
        let str = ''
        for (let i = 0; i < length; i++) {
          str += this.multipleSelection[i].name + '、'
        }
        this.$message.error(`成功删除了${str}` + '用户')
        this.getUserList()
      } else if (data.code == 400) {
        this.$message.error(data.message)
      } else {
        this.$message.error('删除失败')
      }
      this.multipleSelection = [] // 删除后清空列表
    },
    // 排序
    indexSort(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1
    },
  },
}
</script>

<style lang="less" scoped>
.table-td-headPortrait {
  width: 40px;
  height: 40px;
}
</style>
